# -*- coding: utf-8 -*-
# @Date   : 2020/01/08
# @File   : IC_MaxOvduCnt_ZBC.py
# @Author : yanhaopeng

'''eof
name:最大逾期或透支月数(当前)
code:IC_MaxOvduCnt_ZBC
tableName:
columnName:
groups:征信模块-准入策略
dependencies:IC_DSJ_2D
type:常用指标
dataSourceType:在线指标
description:
eof'''

'''
FACTOR1 = 借贷账户信息(PDA)--基本信息段(PD01A)--账户类型(PD01AD01）∈（D1-非循环贷，R1-循环贷，R2-贷记卡，R4-循环额度下分账户），
            且最新表现信息段(PD01B)--还款状态（PD01BD04）为1-7时，取所有逾期期数的最大值
FACTOR2 = 借贷账户信息(PDA)--基本信息段(PD01A)--账户类型(PD01AD01）∈（R3-准贷记卡）,
            且最新表现信息段(PD01B)--还款状态（PD01BD04）为3-7时，取所有逾期期数的最大值-2
FACTOR = max(FACTOR1,FACTOR2)
'''

import sys
import re
import datetime
reload(sys)
sys.setdefaultencoding('utf-8')

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']


def getTable(data, tableName, occurTimes):
    '''
        获取表信息
        :param data:表上层的字典对象
        :param tableName:表的名字
        :param occurTimes:表出现的次数，如果是0代表此表可以不出现，如果是1代表此表必须出现
        :return:该表全部数据
        '''
    table = data.get(tableName)
    if occurTimes == 0:
        if table is None or table == "":
            return [{}]
        elif isinstance(table, list) is False or len(table) == 0:
            return None
        else:
            return data.get(tableName)
    if occurTimes == 1:
        if table == "":
            return [{}]
        if table is None or isinstance(table, list) is False or len(table) == 0:
            return None
        elif len(table) == 0:
            return [{}]
        else:
            return data.get(tableName)


def isfloat(x):
    '''
    判断x为float类型且大于等于0
    :param x:
    :return:
    '''
    try:
        if isinstance(float(x), float) and float(x)>=0:
            if str(x) in ['inf', 'infinity', 'INF', 'INFINITY', 'True']:
                return False
            else:
                return True
        else:
            return False
    except:
        return False

def IC_MaxOvduCnt():
    data = IC_DSJ_2D['data']
    factor = []
    # 借贷账户信息   [1..1]
    PDA = getTable(data, 'PDA', 1)
    if PDA is None:
        return u'缺失值'
    elif PDA == [{}]:
        return 0
    else:
        # 借贷账户信息单元   [0..*]
        PD01 = getTable(PDA[0], 'PD01', 0)
        if PD01 is None:
            return u'缺失值'
        elif PD01 == [{}]:
            return 0
        else:
            for i in PD01:
                try:
                    # 基本信息段   [1..1]
                    PD01A = getTable(i, 'PD01A', 1)
                    # 最新表现信息段   [1..1]
                    PD01B = getTable(i, 'PD01B', 1)
                    if PD01A is None or PD01B is None:
                        factor.append(None)
                    else:
                        # 账户类型   [1..1]
                        PD01AD01 = PD01A[0].get('PD01AD01')
                        if PD01AD01 in null_type_list:
                            factor.append(None)
                        # D1(非循环贷账户),R1(循环贷账户),R2(贷记卡),R4(循环额度下分账户)
                        elif PD01AD01 in ['D1', 'R1', 'R2', 'R4']:
                            if PD01B == [{}]:
                                factor.append(0)
                            else:
                                #还款状态    [1..1]
                                PD01BD04 = PD01B[0].get('PD01BD04')
                                if PD01BD04 not in null_type_list:
                                    if isfloat(PD01BD04) and float(PD01BD04) >=1 and float(PD01BD04) <=7:
                                        factor.append(float(PD01BD04))
                                    else:
                                        factor.append(0)
                                else:
                                    factor.append(None)

                        # 准贷记卡
                        elif PD01AD01 == 'R3':
                            if PD01B == [{}]:
                                factor.append(0)
                            else:
                                #还款状态    [1..1]
                                PD01BD04 = PD01B[0].get('PD01BD04')
                                if PD01BD04 not in null_type_list:
                                    if isfloat(PD01BD04) and float(PD01BD04) >=1 and float(PD01BD04) <=7:
                                        factor.append(float(PD01BD04)-2)
                                    else:
                                        factor.append(0)
                                else:
                                    factor.append(None)
                        else:
                            factor.append(0)
                except:
                    factor.append(None)
                    continue
    #去除None
    factor = filter(lambda x: x is not None, factor)
    if len(factor) == 0:
        return u'缺失值'
    else:
        return max(factor)


result = IC_MaxOvduCnt()

# import json
# ratingRequest = {"legalPerson": u"朱为广", "legalPersonIdCard": "510102196706108511", "creditCode": "123456",
#                  "regNumber": "12345", "relativeDate":u'2019/08/09'}
# with open('F:/hp/IC_DSJ1.json', 'r') as f:
#     IC_DSJ_2D = json.loads(f.read())['IC_DSJ']
# print IC_MaxOvduCnt()